package com.xyoto.community.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author coderFu
 * @create 2021/11/9
 * 开启异步线程的支持
 */

@Configuration
@EnableAsync
@ConfigurationProperties(prefix = "thread-pool")
@PropertySource(value = "classpath:thread_pool.properties",name ="thread_pool.properties",encoding = "utf-8")
@Data
public class ThreadPoolConfig {

    private int maxThreadCount;

    private int coreThreadCount;

    private int keepAliveTime;

    private int queueCapacity;
    /**
     * 线程池前缀
     */
    private String threadNamePrefix;


    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor getAsyncThreadPool(){
       ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
       threadPoolTaskExecutor.setCorePoolSize(coreThreadCount);
       threadPoolTaskExecutor.setMaxPoolSize(maxThreadCount);
       threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveTime);
       threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
       threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
       //当线程池无法处理时，由原线程来处理
       threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
       //初始化
       threadPoolTaskExecutor.initialize();
       return threadPoolTaskExecutor;
    }
}
